package com.zp.servlet;

import com.google.gson.Gson;
import com.zp.common.ResultEnum;
import com.zp.dao.UserDao;
import com.zp.dao.impl.UserDaoImpl;
import com.zp.dao.impl.UserDaoRaw;
import com.zp.domain.User;
import com.zp.utils.Base64Util;
import com.zp.utils.CommonUtil;
import com.zp.utils.MD5Util;
import com.zp.utils.ResultUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet("/user/register")
public class RegisterServlet extends HttpServlet {

	private UserDao userDao;
	private PrintWriter out;

	/**
	 * 将读入的BufferedReader 转换成字符串
	 */
	private String readJSONData(BufferedReader reader) {
		String lineString = null;
		StringBuffer json = new StringBuffer();
		try {
			while ((lineString=reader.readLine())!=null) {
				json.append(lineString);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return json.toString();
	}

	@Override
	public void init() throws ServletException {
		userDao = new UserDaoImpl();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		this.doPost(request, response);
	}


	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");

		// 获取response的写权
		out = response.getWriter();
		Gson gson = new Gson();
		User user = null;

		try {
			String json = CommonUtil.readJSONData(request.getReader());
			user = gson.fromJson(json, User.class);
		} catch (Exception e){
			e.printStackTrace();
			out.print(gson.toJson(ResultUtil.error(ResultEnum.UNKNOWN_ERROR.getCode(), ResultEnum.UNKNOWN_ERROR.getMsg())));
			return;
		}

		String plainText = user.getPassword();
		if (plainText == null) {
			out.print(gson.toJson(ResultUtil.error(ResultEnum.DATA_IS_NULL.getCode(), ResultEnum.DATA_IS_NULL.getMsg())));
			return;
		}
		// 二重加密
		String password = Base64Util.getEncodeBase64(MD5Util.getMD5(plainText));
		user.setPassword(password);
		try {
			int row = userDao.insertRegister(user);
			if (row == 0) {
				out.print(gson.toJson(ResultUtil.error(ResultEnum.USER_IS_EXISTS.getCode(),ResultEnum.USER_IS_EXISTS.getMsg())));
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
			out.print(gson.toJson(ResultUtil.error(ResultEnum.USER_IS_EXISTS.getCode(),ResultEnum.USER_IS_EXISTS.getMsg())));
			return;
		}
		// 返回Ajax数据
		out.print(gson.toJson(ResultUtil.success()));
	}

	@Override
	public void destroy() {
		try {
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
